// 主JavaScript文件

// 文档加载完成事件
document.addEventListener('DOMContentLoaded', function() {
  // 侧边栏菜单激活状态处理
  activateCurrentMenuItem();
  
  // 初始化删除确认对话框
  initDeleteConfirmation();
  
  // 为表单添加验证
  initFormValidation();
  
  // 初始化下拉菜单
  initDropdownMenus();
});

// 处理当前菜单项的激活状态
function activateCurrentMenuItem() {
  const currentPath = window.location.pathname;
  document.querySelectorAll('.sidebar .nav-link, .sidebar .dropdown-item').forEach(link => {
    const href = link.getAttribute('href');
    if (href && currentPath.includes(href) && href !== '#') {
      link.classList.add('active');
      // 如果是下拉菜单中的项目，展开父菜单
      if (link.classList.contains('dropdown-item')) {
        const parentDropdown = link.closest('.dropdown');
        if (parentDropdown) {
          const parentToggle = parentDropdown.querySelector('.dropdown-toggle');
          if (parentToggle) {
            parentToggle.classList.add('active');
            const dropdownMenu = parentDropdown.querySelector('.dropdown-menu');
            if (dropdownMenu) {
              dropdownMenu.classList.add('show');
            }
          }
        }
      }
    }
  });
}

// 初始化下拉菜单
function initDropdownMenus() {
  document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
    toggle.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      
      const parent = this.closest('.dropdown');
      const dropdownMenu = parent.querySelector('.dropdown-menu');
      
      // 切换显示状态
      if (dropdownMenu.classList.contains('show')) {
        dropdownMenu.classList.remove('show');
      } else {
        // 先关闭所有其他打开的下拉菜单
        document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
          if (menu !== dropdownMenu) {
            menu.classList.remove('show');
          }
        });
        dropdownMenu.classList.add('show');
      }
    });
  });
  
  // 点击页面其他位置关闭下拉菜单
  document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown')) {
      document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
        menu.classList.remove('show');
      });
    }
  });
}

// 初始化删除确认对话框
function initDeleteConfirmation() {
  document.querySelectorAll('.btn-delete').forEach(button => {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      if (confirm('确定要删除此记录吗？此操作不可恢复。')) {
        const url = this.getAttribute('data-url');
        deleteResource(url);
      }
    });
  });
}

// 删除资源
function deleteResource(url) {
  fetch(url, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      showToast('删除成功', 'success');
      // 重新加载页面或更新表格
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    } else {
      showToast('删除失败: ' + data.message, 'error');
    }
  })
  .catch(error => {
    showToast('操作失败: ' + error, 'error');
  });
}

// 表单提交通用函数
function submitForm(formId, url, method = 'POST') {
  const form = document.getElementById(formId);
  if (!form) return;
  
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    
    if (!validateForm(form)) return;
    
    const formData = new FormData(form);
    const jsonData = {};
    
    formData.forEach((value, key) => {
      jsonData[key] = value;
    });
    
    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(jsonData)
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        showToast('操作成功', 'success');
        // 跳转到列表页
        setTimeout(() => {
          window.location.href = form.getAttribute('data-redirect') || '/';
        }, 1000);
      } else {
        showToast('操作失败: ' + data.message, 'error');
      }
    })
    .catch(error => {
      showToast('操作失败: ' + error, 'error');
    });
  });
}

// 初始化表单验证
function initFormValidation() {
  const forms = document.querySelectorAll('form[data-validate="true"]');
  forms.forEach(form => {
    form.querySelectorAll('input, select, textarea').forEach(field => {
      if (field.hasAttribute('required')) {
        field.addEventListener('blur', function() {
          validateField(this);
        });
      }
    });
  });
}

// 验证单个表单字段
function validateField(field) {
  const errorElement = field.nextElementSibling;
  
  if (field.value.trim() === '') {
    field.classList.add('is-invalid');
    if (errorElement && errorElement.classList.contains('invalid-feedback')) {
      errorElement.textContent = '此字段不能为空';
    } else {
      const feedback = document.createElement('div');
      feedback.className = 'invalid-feedback';
      feedback.textContent = '此字段不能为空';
      field.parentNode.insertBefore(feedback, field.nextSibling);
    }
    return false;
  } else {
    field.classList.remove('is-invalid');
    if (errorElement && errorElement.classList.contains('invalid-feedback')) {
      errorElement.textContent = '';
    }
    return true;
  }
}

// 验证整个表单
function validateForm(form) {
  let isValid = true;
  form.querySelectorAll('input, select, textarea').forEach(field => {
    if (field.hasAttribute('required')) {
      if (!validateField(field)) {
        isValid = false;
      }
    }
  });
  return isValid;
}

// 显示通知消息
function showToast(message, type = 'info') {
  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  toast.textContent = message;
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.classList.add('show');
  }, 100);
  
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, 3000);
}

// 加载分页数据
function loadPageData(url, tableId, columns, pageSize = 10) {
  const table = document.getElementById(tableId);
  if (!table) return;
  
  let currentPage = 1;
  
  function fetchData(page) {
    const params = new URLSearchParams(window.location.search);
    params.set('current', page);
    params.set('size', pageSize);
    
    // 获取搜索表单中的所有输入值
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
      const formData = new FormData(searchForm);
      formData.forEach((value, key) => {
        // 只添加有值的参数
        if (value.trim() !== '') {
          params.set(key, value);
        }
      });
    }
    
    fetch(`${url}?${params.toString()}`)
      .then(response => response.json())
      .then(result => {
        if (result.code === 200) {
          renderTable(result.data);
          renderPagination(result.data);
          // 更新总记录数
          const totalCountElement = document.getElementById('totalCount');
          if (totalCountElement) {
            totalCountElement.textContent = result.data.total || 0;
          }
        } else {
          showToast('加载数据失败: ' + result.message, 'error');
        }
      })
      .catch(error => {
        showToast('加载数据失败: ' + error, 'error');
      });
  }
  
  function renderTable(data) {
    const tbody = table.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (data.records.length === 0) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = columns.length + 1; // +1 for actions column
      td.textContent = '暂无数据';
      td.className = 'text-center';
      tr.appendChild(td);
      tbody.appendChild(tr);
      return;
    }
    
    // 获取表头的列样式
    const headerCells = table.querySelectorAll('thead th');
    const headerStyles = Array.from(headerCells).map(th => {
      return {
        width: th.style.width || '',
        textAlign: th.style.textAlign || ''
      };
    });
    
    data.records.forEach(item => {
      const tr = document.createElement('tr');
      
      columns.forEach((column, index) => {
        const td = document.createElement('td');
        
        // 应用表头的宽度样式
        if (index < headerStyles.length && headerStyles[index].width) {
          td.style.width = headerStyles[index].width;
        }
        if (index < headerStyles.length && headerStyles[index].textAlign) {
          td.style.textAlign = headerStyles[index].textAlign;
        }
        
        if (typeof column.render === 'function') {
          td.innerHTML = column.render(item[column.field], item);
        } else {
          td.textContent = item[column.field] || '';
        }
        tr.appendChild(td);
      });
      
      // 操作列
      const actionsTd = document.createElement('td');
      actionsTd.className = 'actions';
      
      // 如果存在表头样式，应用到操作列
      const lastHeaderStyle = headerStyles[headerStyles.length - 1];
      if (lastHeaderStyle && lastHeaderStyle.width) {
        actionsTd.style.width = lastHeaderStyle.width;
      }
      
      // 获取当前URL路径前缀，比如 /customer、/contact 等
      const pathPrefix = window.location.pathname.split('/')[2];
      
      // 查看按钮
      const viewBtn = document.createElement('a');
      viewBtn.href = `/crm/${pathPrefix}/detail/${item.id}`;
      viewBtn.className = 'btn btn-sm btn-info';
      viewBtn.textContent = '查看';
      
      // 编辑按钮
      const editBtn = document.createElement('a');
      editBtn.href = `/crm/${pathPrefix}/edit/${item.id}`;
      editBtn.className = 'btn btn-sm btn-primary';
      editBtn.style.margin = '0 4px'; // 添加左右间距
      editBtn.textContent = '编辑';
      
      // 删除按钮
      const deleteBtn = document.createElement('button');
      deleteBtn.className = 'btn btn-sm btn-danger btn-delete';
      deleteBtn.setAttribute('data-url', `/crm/api/${pathPrefix}/${item.id}`);
      deleteBtn.textContent = '删除';
      
      actionsTd.appendChild(viewBtn);
      actionsTd.appendChild(editBtn);
      actionsTd.appendChild(deleteBtn);
      
      tr.appendChild(actionsTd);
      tbody.appendChild(tr);
    });
  }
  
  function renderPagination(data) {
    const pagination = document.querySelector('.pagination');
    if (!pagination) return;
    
    pagination.innerHTML = '';
    
    // 上一页
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${data.current === 1 ? 'disabled' : ''}`;
    const prevLink = document.createElement('a');
    prevLink.className = 'page-link';
    prevLink.href = '#';
    prevLink.textContent = '上一页';
    prevLi.appendChild(prevLink);
    
    // 下一页
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${data.current === data.pages ? 'disabled' : ''}`;
    const nextLink = document.createElement('a');
    nextLink.className = 'page-link';
    nextLink.href = '#';
    nextLink.textContent = '下一页';
    nextLi.appendChild(nextLink);
    
    pagination.appendChild(prevLi);
    
    // 页码
    for (let i = 1; i <= data.pages; i++) {
      if (
        i === 1 ||
        i === data.pages ||
        (i >= data.current - 2 && i <= data.current + 2)
      ) {
        const li = document.createElement('li');
        li.className = `page-item ${i === data.current ? 'active' : ''}`;
        const link = document.createElement('a');
        link.className = 'page-link';
        link.href = '#';
        link.textContent = i;
        link.addEventListener('click', function(e) {
          e.preventDefault();
          currentPage = i;
          fetchData(currentPage);
        });
        li.appendChild(link);
        pagination.appendChild(li);
      } else if (
        i === data.current - 3 ||
        i === data.current + 3
      ) {
        const li = document.createElement('li');
        li.className = 'page-item disabled';
        const link = document.createElement('a');
        link.className = 'page-link';
        link.textContent = '...';
        li.appendChild(link);
        pagination.appendChild(li);
      }
    }
    
    pagination.appendChild(nextLi);
    
    // 事件处理
    prevLink.addEventListener('click', function(e) {
      e.preventDefault();
      if (data.current > 1) {
        currentPage = data.current - 1;
        fetchData(currentPage);
      }
    });
    
    nextLink.addEventListener('click', function(e) {
      e.preventDefault();
      if (data.current < data.pages) {
        currentPage = data.current + 1;
        fetchData(currentPage);
      }
    });
  }
  
  // 初始加载第一页
  fetchData(currentPage);
  
  // 搜索表单事件
  const searchForm = document.getElementById('searchForm');
  if (searchForm) {
    searchForm.addEventListener('submit', function(e) {
      e.preventDefault();
      currentPage = 1;
      fetchData(currentPage);
    });
    
    // 重置按钮
    const resetBtn = searchForm.querySelector('button[type="reset"]');
    if (resetBtn) {
      resetBtn.addEventListener('click', function() {
        setTimeout(() => {
          currentPage = 1;
          fetchData(currentPage);
        }, 100);
      });
    }
  }
} 